package DAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import connections.ConnectionsFactory;

import util.KMLUtil;
import util.SpatialQueries;

import model.kml.LatLon;

public class RotasDAO {
	
	Log logger = LogFactory.getLog(RotasDAO.class);

	private Connection connection;
	
	public RotasDAO() {
		try {
			connection = ConnectionsFactory.getConnection();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}



	public RotasDAO(Connection connection) {
		super();
		this.connection = connection;
	}
	
	public List<Integer> buscarCaminhoes(){
		String sql = SpatialQueries.BUSCA_CAMINHOES;
		PreparedStatement statement = null;
		ResultSet rs = null;
		List<Integer> list = new ArrayList<Integer>();
		try{
			statement = connection.prepareStatement(sql);
			rs = statement.executeQuery();
			while(rs.next()){
				list.add(new Integer(rs.getInt("COD_CAMINHAO")));
			}
		}catch (Exception e){
			logger.error(e.getMessage());
		}
		
		return list;
	}



	public void cadastrarRotas(List<LatLon> markers){
		String kmlLineString = KMLUtil.gerarKMLLineFromList(markers);
		
		logger.info("Cadastrando rota");
		
		String sql = SpatialQueries.INSERT_ROTA;
		sql = sql.replace(SpatialQueries.GEOM_TAG, kmlLineString);
		PreparedStatement statement = null;
		try{
			statement = connection.prepareStatement(sql);
			statement.execute();
			statement.close();
		}catch (Exception e){
			logger.error(e.getMessage());
		}
		
		
	}
}
